/**

Hello!  Welcome to <b>PiggyTD</b>.

<br><br>

This is a piggy-based tower defense game.

<br><br>

<i>- Allison and Jack</i>

*/

// global variables
int WINDOW_SIZE = 500;
int GRID_SIZE = 10;
int GRID_LENGTH = WINDOW_SIZE / GRID_SIZE;
GridObject[][] grid = new GridObject[GRID_LENGTH][GRID_LENGTH];

void setup() 
{
 
  size(WINDOW_SIZE, WINDOW_SIZE);
  background(#FFFFFF);
  
  // draw grids for testing
  for(int i = 0; i < width; i+= GRID_SIZE) 
  {
    line(i, 0, i, height);
    line(0, i, width, i);
  }
  fillRandom(10);
  
}

void draw()
{
  // draw whatever is at each grid 
  for(int i = 0; i < GRID_LENGTH; i++)
  {
    for(int j = 0; j < GRID_LENGTH; j++)
    {
      if(grid[i][j] != null)
      {
        grid[i][j].draw(i, j);
      }
    }
  }
  
}

// Try to insert random piggy towers
void fillRandom(int numPiggyTowers)
{
  int randomX, randomY;
  PiggyTower pt;
  for(int i=0; i<numPiggyTowers; i++)
  {
    randomX = (int)random(0, GRID_LENGTH-1);
    randomY = (int)random(0, GRID_LENGTH-1);
    pt = new PiggyTower();
    if (checkSpaceFree(pt.getImageSize(), randomX, randomY))
    {
      println("GG Space Free: (" + randomX + ", " + randomY + ")\n");
      // Fill top left with actual Piggy Object
      grid[randomX][randomY] = pt;
      for(int j=1; j<pt.getImageSize(); j++)
      {
        for(int k=1; k<pt.getImageSize(); k++)
        {
          grid[randomX+j][randomY+k] = new FillerGrid();
        }
      }
    }
  }
}

// Checks whether you can place a square object into position x and y
boolean checkSpaceFree(int size, int x, int y)
{
  for(int i=0; i<size; i++)
  {
    for (int j=0; j<size; j++)
    {
      // Check that you don't go past the boundary of the grid
      if ((x+i) >= GRID_LENGTH || (y+j) >= GRID_LENGTH)
      {
        return false;
      }
      // Check that spot is not already occupied
      if(grid[x+i][y+j] != null)
      {
        return false;
      }
    }
  }
  return true;
}
